package com.etlmaster.executor.processors.Table;

import java.util.Map;

import com.etlmaster.executor.utils.DataCollectionUtils;
import com.etlmaster.executor.utils.DpExecutorUtils;
import com.etlmaster.executor.utils.LogWriter;
import com.etlmaster.executor.utils.MultiTenantDataSourceUtils;
import com.etlmaster.executor.utils.StepState;
import com.etlmaster.jdbc.JdbcTemplate;

/**
 * 删除表执行器
 * 
 * @author Wugf
 * @date 2016-03-08
 */
public class DropTableProcessor {
	private String userName;
	private String password;
	private String dsName;
	private String tableName;
	private void init(String dsName,String tableName){
		this.dsName=dsName;
		this.tableName=tableName;
		//getdbInfo();
	}
	
	public int process(String dsName,String tableName,Map<String,Object> variables){
		init(dsName,tableName);
		int result=execDrop(variables);
		if(result==StepState.RUNNING_SUCCESSED){
			writeDropTableLog(tableName);
			return StepState.RUNNING_SUCCESSED;
		}else{
			return StepState.RUNNING_FAILED;
		}
		
		
	}
	/*
	 * 删除表日志
	 */
	private void writeDropTableLog(String realTableName) {
		try {
			JdbcTemplate jdbcTemplate = new JdbcTemplate();
			String sql = "delete from tableall where DBNAME=? and dataname=?";
			jdbcTemplate.update(sql, new Object[] { dsName,realTableName});
			
		} catch (Exception e) {
			LogWriter.addLog("WARN","记录建表日志失败{}", dsName, realTableName
					,tableName,
					userName);
			LogWriter.addLog("WARN","异常信息为：{}",e.getMessage());
		}
	}
	private int execDrop(Map<String,Object> variables){
		try{
			JdbcTemplate jdbcTemplate = new JdbcTemplate(MultiTenantDataSourceUtils.getDataSource(dsName, userName, password));
			
			String dsType = DataCollectionUtils.getDsType(dsName);
			StringBuilder sql=new StringBuilder();
			String realTableName=DpExecutorUtils.variableSubstitution(tableName,variables);
			int row = 0;
			//hive需要调用excute方法
			if(dsType.equals("hive")){
				sql.append("drop table ").append(realTableName);
				LogWriter.addLog("INFO","删除表{}",sql.toString());
				jdbcTemplate.execute(sql.toString());
			}else{
				sql.append("DROP TABLE ")
				   .append(realTableName);
				LogWriter.addLog("INFO","删除表{}",sql.toString());
				jdbcTemplate.update(sql.toString());
			}
			writeDropTableLog(realTableName);
		}catch(Exception e){
			LogWriter.addLog("ERROR","删除表失败");
			LogWriter.addLog("ERROR","异常信息为：{}",e.getMessage());
			return StepState.RUNNING_FAILED;
		}
		
		return StepState.RUNNING_SUCCESSED;
	}
	/*
	private void getdbInfo(){
		JdbcTemplate jdbcTemplate =new JdbcTemplate(); 
		
		Map<String,Object> dbUserInfo=DataCollectionUtils.fetchDBUserInfoByTeam(dsName, teamCode, jdbcTemplate);
		userName= dbUserInfo.get("username").toString();
		password=dbUserInfo.get("password").toString();
	}*/

}
